<?php
global $dPconfig;
$task_id = intval( dPgetParam( $_REQUEST, 'task_id', 0 ) );

if ($_POST['save'] != '') {
	$sd = new CDate($_POST['task_start_date'].'080000');
	$sd = $sd->format(FMT_DATETIME_MYSQL);
	$ed = '';
	if (isset($_POST['task_end_date']) && $_POST['task_end_date'] != '') {
		$ed = new CDate($_POST['task_end_date'] . '180000');
		$ed = $ed->format(FMT_DATETIME_MYSQL);
	}

	$task_name = htmlentities(stripslashes($_POST['task_name']), ENT_QUOTES);
	$task_dynamic = isset($_POST['task_dynamic']) ? 1 : 0;
	$task_milestone = isset($_POST['task_milestone']) ? 1 : 0;
	$task_status = isset($_POST['task_status']) ? 0 : -1;
	$task_creator = isset($_POST['task_creator']) ? $_POST['task_creator'] : $AppUI->user_id;

	$q = new DBQuery;
	$q->addTable('tasks');
	$values = array(
		$task_name,
		$_POST['task_parent'], $_POST['task_project'], $task_creator,
		$sd, $_POST['task_duration'], 1, $ed,
		htmlentities(stripslashes($_POST['task_description']), ENT_QUOTES),
		$_POST['task_priority'], $task_creator, 0, 0,
		$task_dynamic, 0, 0, 0, $task_milestone, $task_status
	);
	$fields = 'task_name,task_parent,task_project,task_owner,'.
		'task_start_date,task_duration,task_duration_type,task_end_date,task_description,'.
		'task_priority,task_creator,task_order,task_client_publish,'.
		'task_dynamic,task_access,task_notify,task_type,task_milestone,task_status';
	if ($task_id <= 0) {
		$q->addInsert($fields, $values, true);
		$AppUI->setMsg( 'Task <br/>['.$task_name.']<br/>has been added', UI_MSG_OK);
	}
	else {
		$q->addUpdate($fields, $values, true);
		$q->addWhere('task_id = '.$task_id);
		$AppUI->setMsg( 'Task <br/>['.$task_name.']<br/>has been updated', UI_MSG_OK);
	}
	$q->exec();

	if ($task_id <= 0) {
		$q->clear();
		$q->addTable('tasks');
		$q->addQuery('task_id');
		$q->addWhere('task_name = "'.$task_name.'"');
		$q->addWhere('task_project = '.$_POST['task_project']);
		$q->addWhere('task_creator = '.$AppUI->user_id);
		$task_id = $q->loadResult();
	}

	db_exec('DELETE FROM user_tasks WHERE task_id = '.$task_id);
	if (is_array($_POST['task_members']))
	foreach ($_POST['task_members'] as $uid) {
		$cval = $_POST['contribute_'.$uid];
		$q = 'INSERT INTO '.
				'user_tasks(user_id,user_type,task_id,perc_assignment) ' .
				"values($uid, 0, $task_id, $cval)";
		db_exec($q);
	}

	db_exec('DELETE FROM task_dependencies WHERE dependencies_task_id = '.$task_id);
	if (is_array($_POST['task_predecessors']))
	foreach ($_POST['task_predecessors'] as $p) {
		db_exec("INSERT INTO task_dependencies VALUES($task_id, $p)");
	}

	if ($_POST['task_parent'] == '0') {
		db_exec("UPDATE tasks SET task_parent = $task_id WHERE task_id=$task_id");
	}

	$AppUI->redirect( $AppUI->getPlace() );
}

$df = $AppUI->getPref('SHDATEFORMAT');
$task_project = $_REQUEST['project_id'];
$perms =& $AppUI->acl();

// load the record data
$obj = new CTask();

// check if we are in a subform
if ($task_id > 0 && !$obj->load( $task_id )) {
	$AppUI->setMsg( 'Task' );
	$AppUI->setMsg( 'invalidID', UI_MSG_ERROR, true );
	$AppUI->redirect();
}

$task_parent = isset($_REQUEST['task_parent'])? $_REQUEST['task_parent'] : $obj->task_parent;

// check for a valid project parent
$task_project = intval( $obj->task_project );
if (!$task_project) {
	$task_project = dPgetParam( $_REQUEST, 'task_project', 0 );
	if (!$task_project) {
		$AppUI->setMsg( "badTaskProject", UI_MSG_ERROR );
		$AppUI->redirect();
	}
}

// check permissions
if ( $task_id ) {
	// we are editing an existing task
	$canEdit = $perms->checkModuleItem( $m, 'edit', $task_id );
} else {
	// do we have access on this project?
	$canEdit = $perms->checkModuleItem( 'projects', 'view', $task_project );
	// And do we have add permission to tasks?
	if ($canEdit)
	  $canEdit = $perms->checkModule('tasks', 'add');
}

if (!$canEdit) {
	$AppUI->setMsg('Access denied', UI_MSG_ERROR);
	$AppUI->redirect();
}

//check permissions for the associated project
$canReadProject = $perms->checkModuleItem( 'projects', 'view', $obj->task_project);

$durnTypes = dPgetSysVal( 'TaskDurationType' );

// check the document access (public, participant, private)
if (!$obj->canAccess( $AppUI->user_id )) {
	$AppUI->setMsg('Access denied', UI_MSG_ERROR);
	$AppUI->redirect();
}

// pull the related project
$project = new CProject();
$project->load( $task_project );

$ptasks = array();

function getSpaces($amount){
	if($amount == 0) return '';
	return str_repeat('&nbsp;', $amount);
}

function constructTaskTree($task_data, $depth = 0){
	global $projTasks, $all_tasks, $parents, $task_parent_options, $task_parent, $task_id, $ptasks;

	$projTasks[$task_data['task_id']] = $task_data['task_name'];

	$selected = $task_data['task_id'] == $task_parent ? 'selected="selected"' : '';
	$task_data['task_name'] = strlen($task_data[1]) > 45 ?
		substr($task_data['task_name'],0, 45).'...' : $task_data['task_name'];

	$task_parent_options .= '<option value="'.$task_data['task_id'].'" '.$selected.'>'.
		getSpaces($depth*3).dPFormSafe($task_data['task_name']).'</option>';
	$ptasks[$task_data['task_id']] = '<img src="images/blank.gif" width="'.(12 * $depth).'" height="1"/>'.$task_data['task_name'];

	if (isset($parents[$task_data['task_id']])) {
		foreach ($parents[$task_data['task_id']] as $child_task) {
			if ($child_task != $task_id)
				constructTaskTree($all_tasks[$child_task], ($depth+1));
		}
	}
}

function build_date_list(&$date_array, $row) {
	global $tracked_dynamics, $project;
	// if this task_dynamic is not tracked, set end date to proj start date
	if ( !in_array($row['task_dynamic'], $tracked_dynamics) )
		$date = new CDate( $project->project_start_date );
	elseif ($row['task_milestone'] == 0) {
		$date = new CDate($row['task_end_date']);
	} else {
		$date = new CDate($row['task_start_date']);
	}
	$sdate = $date->format('%d/%m/%Y');
	$shour = $date->format('%H');
	$smin = $date->format('%M');

	$date_array[$row['task_id']] = array($row['task_name'], $sdate, $shour, $smin);
}

$q = new DBQuery();
$q->addTable('users', 'u');
$q->addTable('contacts', 'c');
$q->addTable('project_contacts', 'pc');
$q->addQuery('user_id,contact_first_name,contact_last_name');
$q->addWhere('pc.contact_id = u.user_id AND u.user_contact = c.contact_id AND pc.project_id = '.$task_project);
$q->addOrder('contact_first_name');
$sql = $q->prepare();
$users = db_loadHashList($sql, 'user_id');

$dtasks = array();
$members = array();
if ($task_id > 0) {
	$sql = 'SELECT * FROM user_tasks WHERE task_id = '.$task_id;
	$members = db_loadHashList($sql, 'user_id');

	$sql = 'SELECT * FROM task_dependencies WHERE dependencies_task_id = '.$task_id;
	$dtasks = db_loadHashList($sql, 'dependencies_req_task_id');
}
else {
	$members[$AppUI->user_id] = array('perc_assignment' => 100);
}

$q->clear();
$q->addTable('holidays');
$q->addQuery('hdate,description');
$q->addOrder('hdate');
$holidays = $q->loadHashList();

// let's get root tasks
$sql = 'SELECT task_id, task_name, task_end_date, task_start_date, task_milestone, task_parent, task_dynamic
		FROM tasks
		WHERE task_project = '.$task_project.' AND task_id = task_parent
        ORDER BY task_start_date';

$root_tasks = db_loadHashList($sql, 'task_id');

$projTasks           = array();
$task_parent_options = '';

// Now lets get non-root tasks, grouped by the task parent
$sql = 'SELECT task_id, task_name, task_end_date, task_start_date, task_milestone, task_parent, task_dynamic
		FROM tasks
		WHERE task_project = '.$task_project.' AND task_id != task_parent
		ORDER BY task_start_date';

$parents = array();
$projTasksWithEndDates = array( $obj->task_id => $AppUI->_('None') );//arrays contains task end date info for setting new task start date as maximum end date of dependenced tasks
$all_tasks = array();
$sub_tasks = db_exec($sql);
if ($sub_tasks) {
	while ($sub_task = db_fetch_assoc($sub_tasks)) {
		// Build parent/child task list
		$parents[$sub_task['task_parent']][] = $sub_task['task_id'];
		$all_tasks[$sub_task['task_id']] = $sub_task;
		build_date_list($projTasksWithEndDates, $sub_task);
	}
}

// let's iterate root tasks
foreach ($root_tasks as $root_task) {
	build_date_list($projTasksWithEndDates, $root_task);
	if ($root_task['task_id'] != $task_id)
		constructTaskTree($root_task);
}

// setup the title block
$ttl = $task_id > 0 ? 'Edit Task' : 'Add Task';
$titleBlock = new CTitleBlock( $ttl );
$titleBlock->addButton( 'tasks list', 'index.php?m=tasks' );
$titleBlock->addCell();
$titleBlock->show();

//Dynamic tasks are by default now off because of dangerous behavior if incorrectly used
if ( is_null($obj->task_dynamic) ) $obj->task_dynamic = 0 ;

$can_edit_time_information = $obj->canUserEditTimeInformation();

if (intval($obj->task_start_date))
	$start_date = new CDate($obj->task_start_date);
else if ($task_id != 0)
	$start_date = null;
else
	$start_date = new CDate();

$end_date = intval( $obj->task_end_date ) ? new CDate( $obj->task_end_date ) : new CDate();
$task_creator = isset($obj->task_creator) ? $obj->task_creator : $AppUI->user_id;
?>
<script language="JavaScript">
Calendar.enabled = true;

function doCancel() {
	go('?<?=$AppUI->getPlace()?>');
}

function doCheckSubmit()
{
	var t = $('idTaskName');
	if (t.value.trim() == '') {
		t.focus();
		alert('Missing task name');
		return false;
	}
	var d = $('idDuration');
	if (d.value.trim() == '') {
		doCalcDuration();
	}
	return true;
}

</script>
<form name="SimpleTaskEditForm" action="?m=tasks&a=simpleaddedit&project_id=<?=$task_project?>" method="post"
	onsubmit="return doCheckSubmit()">
	<input name="task_id" type="hidden" value="<?=$task_id?>" />
	<input name="task_project" type="hidden" value="<?=$task_project?>" />
	<input name="task_creator" type="hidden" value="<?=$task_creator?>" />
	<input name="task_percent_complete" type="hidden" value="0"/>
<table border="0" cellpadding="4" cellspacing="0" width="100%">
<tr>
	<td class="tabon">[&nbsp;<?=$project->project_short_name?>&nbsp;]&nbsp;<?=$project->project_name?></td>
	<td width="100%">&nbsp;</td>
</tr>
</table>
<table border="0" cellpadding="4" cellspacing="0" width="100%" class="infopanel">
<tr>
	<td nowrap="nowrap">
		<input class="button" type="submit" name="save"
				value="<?=$AppUI->_('save')?>"/>
		<input class="button" type="button" name="cancel"
				value="<?=$AppUI->_('cancel')?>" onClick="doCancel()" />
	</td>
	<td align="right" width="100%">
	<?
		if ($canReadProject) {
			showButton( 'view this project', '?m=projects&a=view&project_id='.$task_project );
		}
		if ($task_id > 0) {
			showButton( 'view this task', '?m=tasks&a=view&task_id='.$obj->task_id );
		}
	?>&nbsp;
	</td>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="4" width="100%" class="subinfopanel">
<tr>
	<td align="right" nowrap="nowrap" width="90px">
		<?=$AppUI->_( 'Task Name' )?>
	</td>
	<td>
		<input id="idTaskName" tabindex="1" type="text" class="text" name="task_name"
			value="<?=$obj->task_name?>" style="width: 300px" maxlength="255" />
	</td>
	<td rowspan="2">&nbsp;</td>
	<td align="right" nowrap="nowrap">
		<?=$AppUI->_( 'Start' )?>
	</td>
	<td>
		<input id="idDateFrom" type="hidden" name="task_start_date" onchange="doCheckDate(this)"
				value="<?=$start_date ? $start_date->format( FMT_TIMESTAMP_DATE ) : ''?>" />
		<input id="idDateFromD" type="text" style="width: 60px"
				value="<?=$start_date ? $start_date->format( $df ) : ''?>"
				class="text" disabled="disabled" />
	</td>
	<td>
		<img id="idDateFromB" src="images/calendar.gif" title="<?=$AppUI->_('Calendar')?>">
	</td>
	<td rowspan="2"><img src="images/blank.gif" width="16"/></td>
	<td align="right" nowrap="nowrap"><?=$AppUI->_( 'Priority' )?></td>
	<td nowrap="nowrap">
		<?=arraySelect( $priority, 'task_priority',
			'tabindex="3" size="1" class="text" style="text-transform: capitalize; width: 72px"',
			$obj->task_priority, true )?>
	</td>
	<td width="100%"></td>
</tr>
<tr>
	<td align="right">
		<?=$AppUI->_( 'Parent' )?>
	</td>
	<td>
		<select tabindex="2" name='task_parent' class='text' style="width: 308px">
			<option value='0'><?=$AppUI->_('None')?></option>
			<?=$task_parent_options?>
		</select>
	</td>
	<td align="right">
		<?=$AppUI->_( 'Finish' )?>
	</td>
	<td>
		<input id="idDateTo" type="hidden" name="task_end_date" onchange="doCheckDate(this)"
				value="<?=$end_date ? $end_date->format( FMT_TIMESTAMP_DATE ) : ''?>" />
		<input id="idDateToD" type="text" style="width: 60px"
				value="<?=$end_date ? $end_date->format( $df ) : ''?>"
				class="text" disabled="disabled" />
	</td>
	<td>
		<img id="idDateToB" src="images/calendar.gif" title="<?=$AppUI->_('Calendar')?>">
	</td>
	<td align="right" nowrap="nowrap">
		<?=$AppUI->_( 'Duration' )?>
	</td>
	<td nowrap="nowrap">
		<input id="idDuration" tabindex="4" type="text" style="width: 36px; text-align: right" name="task_duration"
			value="<?=$obj->task_duration ? $obj->task_duration : $dPconfig['daily_working_hours']?>"
			onchange="doCalcEffort()"/> h&nbsp;
		<img src="images/calc.png" title="Calculate Duration" class="ico clickable" onclick="doCalcDuration()"/>
	</td>
</tr>
<tr>
	<td align="right" valign="top">
		<?=$AppUI->_( 'Description' )?>
	</td>
	<td colspan="8">
		<textarea tabindex="5" name="task_description" style="width: 600px; height: 50px"><?=html_entity_decode($obj->task_description)?></textarea>
	</td>
</tr>
<tbody id="idDetails">
<tr>
	<td>&nbsp;</td>
	<td valign="top">
		<?=$AppUI->_( 'Predecessors' )?>
	</td>
	<td colspan="2">&nbsp;</td>
	<td valign="top">
		<?=$AppUI->_( 'Members' )?>
	</td>
</tr>
<tr>
	<td>&nbsp;</td>
	<td>
		<div class='text' style="width: 300px; height: 150px; overflow: auto; overflow-x: hidden">
			<table border="0" cellspacing="2" cellpadding="0" width="92%">
			<?
				foreach ($ptasks as $id => $name) {
					$cid = 'idTCB'.$id;
					echo '<tr class="second">'.
						'<td width="18px">' .
							'<input id="'.$cid.'" type="checkbox" name="task_predecessors[]" value="'.$id.'" ' .
								(isset($dtasks[$id]) ? 'checked="true"' : '').
								'onclick="selectItem(this)"/>' .
						'</td>'.
						'<td nowrap="nowrap"><label for="'.$cid.'">'.$name.'</label></td>'.
						'</tr>';
				}
			?>
			</table>
		</div>
	</td>
	<td colspan="2">&nbsp;</td>
	<td colspan="5">
		<div class='text' style="width: 240px; height: 150px; overflow: auto">
			<table border="0" cellspacing="2" cellpadding="0" width="92%">
			<?
				$mlist = '';
				$alist = '';
				foreach ($users as $id => $u) {
					$active = isset($members[$id]);
					$cid = 'idMCB'.$id;
					$data = '<tr style="border-bottom: 1px solid grey">'.
						'<td width="18px">' .
							'<input id="'.$cid.'" type="checkbox" name="task_members[]" value="'.$id.'" '.
								'onclick="selectItem(this, 1)" '.($active ? 'checked' : '').'/>' .
						'</td>'.
						'<td nowrap="nowrap" width="100%"><label for="'.$cid.'">'.
							$u['contact_first_name'].' '.$u['contact_last_name'].
						'</label></td><td>' .
							createSpinBox('contribute_'.$id, $active ? $members[$id]['perc_assignment'] : 0,
								0, 100, '%', 5, !$active) .
						'</td></tr>';
					if ($active)
						$mlist .= $data;
					else
						$alist .= $data;
				}
				echo $mlist . $alist;
			?>
			</table>
		</div>
	</td>
</tr>
<tr>
	<td>&nbsp;</td>
	<td>
		<table cellspacing="2" cellpadding="0" border="0">
		<tr>
			<td><input id="idTaskActive" type="checkbox" name="task_status" value="0"
					<?=$obj->task_status >= 0 ? 'checked="true"' : ''?>/></td>
			<td><label for="idTaskActive">Active</label></td>
			<td>&nbsp;</td>
			<td><input id="idTaskMilestone" type="checkbox" name="task_milestone" value="1"
					<?=$obj->task_milestone == 1 ? 'checked="true"' : ''?>/></td>
			<td><label for="idTaskMilestone">Milestone</label></td>
			<td>&nbsp;</td>
			<td><input id="idTaskDynamic" type="checkbox" name="task_dynamic" value="1"
					<?=$obj->task_dynamic == 1 ? 'checked="true"' : ''?>/></td>
			<td><label for="idTaskDynamic">Dynamic</label></td>
			<!--td>&nbsp;</td>
			<td><input id="idTaskTracking" type="checkbox" name="task_tracking" value="1"/></td>
			<td><label for="idTaskTracking">Tracking</label></td-->
		</tr>
		</table>
	</td>
	<td colspan="2">&nbsp;</td>
	<td colspan="5" align="right" style="padding-right: 25px">
		Total Efforts <input id="idEffort" type="text" value="" style="width: 36px; text-align: right" readonly="true"/> h
	</td>
</tr>
</tbody>
</table>
</form>
<script>
function selectItem(cb, e)
{
	cb.parentNode.parentNode.className = cb.checked ? 'active' : 'second';
	if (e != undefined) {
		var s = $('idContribute_' + cb.value);
		if (s != null) s.disabled = !cb.checked;
		doCalcEffort();
	}
}

var hdays = [];
<?
	foreach ($holidays as $d => $s) {
		echo "hdays[Date.parse('".str_replace('-', '/', $d)."')] = true;\n";
	}
?>

function doCheckDate(f)
{
	var fd = Date.parseDate($('idDateFrom').value, '<?=FMT_TIMESTAMP_DATE?>');
	var td = Date.parseDate($('idDateTo').value, '<?=FMT_TIMESTAMP_DATE?>');

	if (fd > td) {
		if (f.id == 'idDateFrom') {
			$('idDateTo').value = $('idDateFrom').value;
			$('idDateToD').value = fd.print('<?=$df?>');
		}
		else {
			$('idDateFrom').value = $('idDateTo').value;
			$('idDateFromD').value = td.print('<?=$df?>');
		}
	}

	setTimeout('doCalcDuration()', 100);
}

function doCalcDuration()
{
	var d = $('idDuration');
	var fd = Date.parseDate($('idDateFromD').value, '<?=$df?>');
	var td = Date.parseDate($('idDateToD').value, '<?=$df?>');
	var h, t = parseInt('<?=$dPconfig['daily_working_hours']?>', 10);
	var wdays = '<?=$dPconfig['cal_working_days']?>';
	var msec_per_day = Date.DAY;

	if (t == 0 || t == NaN) t = 8;
	h = t * (((td - fd) / msec_per_day) + 1);
	while (fd <= td) {
		var z = wdays.indexOf(fd.getDay());
		if (z < 0 || (z % 2 == 1) || hdays[fd.getTime()]) h -= t;
		fd.setTime(fd.getTime() + msec_per_day);
	}
	d.value = h;
	doCalcEffort();
}

var uids = [<?=implode(',', array_keys($users))?>];

function doCalcEffort()
{
	var e = 0.0;
	var d = $('idDuration').value.trim();
	if (d == '') return;
	d = parseFloat(d);
	for (i in uids) {
		var c = $('idContribute_'+uids[i]);
		if (c.disabled) continue;
		e += d * parseInt(c.value, 10) / 100;
	}
	$('idEffort').value = e;
}

function doInitEffortHandlers()
{
	for (i in uids) {
		var c = $('idContribute_'+uids[i]);
		c.onchange = doCalcEffort;
	}
	doCalcEffort();
}

setTimeout('doInitEffortHandlers()', 150);
</script>
